<template>
  <div>
    <div
      class="text-danger mb10"
      v-if="enableDataScope && mode == 'design'"
    >
      {{ $t("formgen.deptSelect.dataScopeDesc") }}
      （{{ $t("formgen.deptSelect.dataScopeDesc_2") }}）
    </div>
    <el-input
      v-model="showValue"
      prefix-icon="ele-User"
      readonly
      :disabled="disabled"
      @click="handleShow"
    />
    <el-dialog
      v-model="dialogVisible"
      title="部门选择"
      width="30%"
      append-to-body
    >
      <el-tree
        ref="deptTreeRef"
        :data="data"
        :props="defaultProps"
        default-expand-all
        :show-checkbox="!single"
        @node-click="handleNodeClick"
        check-strictly
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="TDeptSelect">
import { ref, computed, defineProps, onMounted, useAttrs } from "vue";
import { getDeptTreeRequest } from "../../../api";
import { formEmits, formItemProps, useFormItem } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";
import { Session } from "@/utils/storage";
import { userInfoKey } from "@/utils/auth";
import { useRoute } from "vue-router";
import { useUserInfo } from "@/stores/userInfo";
import { ElTree } from "element-plus";

interface DeptNode {
  id: string;
  name: string;
  children?: DeptNode[];
}

const props = defineProps({
  ...formItemProps,
  single: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  },
  defaultCurrentDept: {
    type: Boolean,
    default: false
  },
  enableDataScope: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(formEmits);

const { changeValue } = useFormItem(props, emits, true);

const data = ref<DeptNode[]>([]);
const showValue = ref<string[]>([]);
const dialogVisible = ref(false);

const defaultProps = {
  children: "children",
  label: "name",
  disabled: false
};

/**
 * 判断数组是否是空的
 */
const isEmptyArray = (arr: any[]) => {
  return !arr || !arr.length;
};

const attrs = useAttrs();
const formKey = useRoute().params.key;

const userInfoStore = useUserInfo();

onMounted(async () => {
  const res = await getDeptTreeRequest({
    formKey: formKey,
    formItemId: attrs.dId
  });
  data.value = res.data;
  if (props.value && Array.isArray(props.value) && !isEmptyArray(props.value)) {
    showValue.value = props.value?.map((item: any) => item.name) || [];
  }
  // 默认值是空的 默认当前用户
  if (props.defaultCurrentDept) {
    // && isEmptyArray(props.value as any[]) TODO: 存在获取登录用户信息 设置的问题 @ chd
    const setDefaultDept = (user: any) => {
      if (!user?.dept) {
        return;
      }
      changeValue.value = [{ name: user?.dept?.deptName, id: user?.dept.id }];
      showValue.value = changeValue.value.map((item: any) => item.name).join(",");
    };
    if (Session.get(userInfoKey)) {
      const userInfos = Session.get(userInfoKey);
      setDefaultDept(userInfos);
    } else {
      await userInfoStore.getApiUserInfo().then((res: any) => {
        setDefaultDept(res);
      });
    }
  }
});

const handleShow = () => {
  if (props.disabled || props.readonly) return;
  dialogVisible.value = true;
};
const deptTreeRef = ref<InstanceType<typeof ElTree>>();

const handleSubmit = () => {
  const checkedNodes = deptTreeRef.value?.getCheckedNodes() || [];
  changeValue.value = checkedNodes.map(item => ({
    name: item.name,
    id: item.id
  }));
  dialogVisible.value = false;
  if (changeValue.value) {
    showValue.value = changeValue.value.map((item: any) => item.name);
  }
};

const handleNodeClick = (data: DeptNode) => {
  if (!props.single) return;

  changeValue.value = [{ name: data.name, id: data.id }];
  dialogVisible.value = false;
  showValue.value = changeValue.value.map((item: any) => item.name);
};
</script>
